package com.tanhua.server.controller;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.db.UserInfo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    /*
        保存用户资料
        post 请求
        Body参数
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo info,
                                       @RequestHeader("Authorization")String token){
        //1.判断token,看是否登录
        boolean verifyToken = JwtUtils.verifyToken(token);
        /*if (!verifyToken){
            //如果非verifyToken
            throw new RuntimeException("用户未登录");
        }
        //2.解析token(用户id),如果正常的话就解析;
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);*/
        Long id= UserHolder.getUserId();
        //3.将用户id设置到info对象
        info.setId(id);
        //4.调用service
        userService.saveUserInfo(info);

        return ResponseEntity.ok(null);
    }

    /*
        设置头像:
        POST /loginReginfo/head
        参数:
            headPhoto文件(头像)
            请求参数是文件,不需要关请求方式和参数类型
            请求头参数:Authorization
            返回值:void
     */
    @PostMapping("/loginReginfo/head")
        public ResponseEntity head(MultipartFile headPhoto,
                         @RequestHeader("Authorization")String token) throws IOException {
        //1.获取参数
        boolean verifyToken = JwtUtils.verifyToken(token);
        /*if (!verifyToken){
            throw  new RuntimeException("用户未登录");
        }
        //2.解析token
        Claims claims = JwtUtils.getClaims(token);
        Long id = claims.get("id", Long.class);*/
        Long id= UserHolder.getUserId();
        //3.调用service
        userService.head(id,headPhoto);
        //4.不需要返回值
        return ResponseEntity.ok(null);
    }
}
